<?php

namespace Modules\Permission\Http\Controllers;
use Modules\Common\Http\Controllers\CommonController;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Modules\Permission\Transformers\RoleResource;
use Modules\Permission\Http\Requests\RoleRequest;
use Modules\Common\Services\CommonService;
use Spatie\Permission\Models\Role;
use Modules\Common\Transformers\CommonResource; 
class RoleController extends CommonController
{
    private $service;      
    public function __construct(CommonService $service) {
        $this->service = $service;
    }

    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        $role = Role::query();
        $items = $this->queryBuilder($role)->aFilters([])->aIncludes([])->aSorts([])->page();
        return $this->success(CommonResource::collection($items));
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Response
     */
    public function store(RoleRequest $request)
    {
        $permissions = $request->permissions = [1,2,3,4,5,6,7,8,9];
        $this->service->setPermission(new Role(),array_merge($request->all(),[
            'guard_name'=>'admin'
        ]));
        $result = $this->service->store();
        if(!$result){
            return $this->fail('注册失败！');
        }
        
        $this->service->setPermission($result,$request->permissions);
        $this->service->permission();
        return $this->created( $result);
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Response
     */
    public function show(Role $role)
    {
        return $this->success(new RoleResource($role));
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function update(RoleRequest $request, Role $role)
    {
        $permissions = $request->permissions = [1,2,3,4,5,6,7,8,9];
        $this->service->setPermission($role,$permissions);
        $this->service->permission();
        
        $this->service->setPermission($role,$request->all());
        $role = $this->service->update();
        return $role;
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}
